package com.ruoyi.docdraw.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.docdraw.domain.supplier.SupplierInsertVo;
import com.ruoyi.docdraw.domain.supplier.SyncSupplierVo;
import com.ruoyi.docdraw.domain.supplier.SysSupplierVo;
import com.ruoyi.docdraw.mapper.SysSupplierMapper;
import com.ruoyi.docdraw.service.ISysGDPService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.docdraw.domain.SysSupplier;
import com.ruoyi.docdraw.service.ISysSupplierService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 组织供应商Controller
 * 
 * @author lvtian
 * @date 2025-04-02
 */
@RestController
@RequestMapping("/system/supplier")
public class SysSupplierController extends BaseController
{
    @Autowired
    private ISysSupplierService sysSupplierService;

    @Autowired
    private SysSupplierMapper sysSupplierMapper;

    @Autowired
    private ISysGDPService sysGDPService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysRoleService roleService;
    /**
     * 查询组织供应商列表
     */
    @PreAuthorize("@ss.hasPermi('docdraw:supplier:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDept dept)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        startPage();
        if(!user.isAdmin()){
            dept.setParentId(user.getDeptId());
        }
        List<SysDept> depts = deptService.selectDeptList(dept);
        return getDataTable(depts);
    }

    /**
     * 导出组织供应商列表
     */
    @PreAuthorize("@ss.hasPermi('docdraw:supplier:export')")
    @Log(title = "组织供应商", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysSupplier sysSupplier)
    {
        List<SysSupplier> list = sysSupplierService.selectSysSupplierList(sysSupplier);
        ExcelUtil<SysSupplier> util = new ExcelUtil<SysSupplier>(SysSupplier.class);
        util.exportExcel(response, list, "组织供应商数据");
    }

    /**
     * 获取组织供应商详细信息
     */
    @PreAuthorize("@ss.hasPermi('docdraw:supplier:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable("deptId") Long supplierId)
    {

        SysSupplier sysSupplier = sysSupplierMapper.selectSysSupplierBySupplierId(supplierId);
        if(ObjectUtil.isNull(sysSupplier)){
            return error("当前所选组织并非供应商！");
        }
        return success(sysSupplierService.selectSysSupplierBySupplierId(supplierId));
    }

    /**
     * 新增组织供应商
     */
    @PreAuthorize("@ss.hasPermi('docdraw:supplier:add')")
    @Log(title = "组织供应商", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SupplierInsertVo sysSupplierInsertVo)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysDept dept = new SysDept();
        dept.setDeptName(sysSupplierInsertVo.getSupplierName());
        Long deptId = user.getDeptId();
        dept.setParentId(deptId);
        // 当前操作的人的部门信息
        SysDept operatorDept = deptService.selectDeptById(deptId);
        dept.setAncestors(operatorDept.getAncestors()+","+deptId);
        dept.setOrderNum(0);
        dept.setLeader(sysSupplierInsertVo.getLeader());
        dept.setEmail(sysSupplierInsertVo.getEmail());
        dept.setPhone(sysSupplierInsertVo.getPhone());
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());
        deptService.insertDept(dept);

        SysSupplier sysSupplier = new SysSupplier();
        BeanUtils.copyBeanProp(sysSupplier, sysSupplierInsertVo);

        sysSupplier.setParentDeptId(deptId);
        sysSupplier.setSupplierId(dept.getDeptId());
        return toAjax(sysSupplierService.insertSysSupplier(sysSupplier));
    }

    /**
     * 修改组织供应商
     */
    @PreAuthorize("@ss.hasPermi('docdraw:supplier:edit')")
    @Log(title = "组织供应商", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SupplierInsertVo sysSupplierInsertVo)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysDept dept = new SysDept();
        Long supplierId = sysSupplierInsertVo.getSupplierId();
        dept.setDeptId(supplierId);

        dept.setDeptName(sysSupplierInsertVo.getSupplierName());
        Long operatorDeptId = user.getDeptId();
        dept.setParentId(operatorDeptId);
        // 当前操作的人的部门信息
        SysDept operatorDept = deptService.selectDeptById(operatorDeptId);
        dept.setAncestors(operatorDept.getAncestors()+","+operatorDeptId);
        dept.setLeader(sysSupplierInsertVo.getLeader());
        dept.setEmail(sysSupplierInsertVo.getEmail());
        dept.setPhone(sysSupplierInsertVo.getPhone());
        dept.setStatus(sysSupplierInsertVo.getStatus());
        deptService.checkDeptDataScope(supplierId);
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(supplierId))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(supplierId) > 0)
        {
            return error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        deptService.updateDept(dept);

        sysSupplierInsertVo.setParentDeptId(operatorDeptId);
        SysSupplier sysSupplier = new SysSupplier();
        BeanUtils.copyBeanProp(sysSupplier, sysSupplierInsertVo);
        return toAjax(sysSupplierService.updateSysSupplier(sysSupplier));
    }

    /**
     * 删除组织供应商
     */
    @PreAuthorize("@ss.hasPermi('docdraw:supplier:remove')")
    @Log(title = "组织供应商", businessType = BusinessType.DELETE)
	@PostMapping("/{supplierId}")
    public AjaxResult remove(@PathVariable Long supplierId)
    {
        if (deptService.hasChildByDeptId(supplierId))
        {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(supplierId))
        {
            return warn("供应商存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(supplierId);
        return toAjax(deptService.deleteDeptById(supplierId));
    }


    @PreAuthorize("@ss.hasPermi('docdraw:supplier:add')")
    @Log(title = "windchill推送供应商信息", businessType = BusinessType.UPDATE)
    @PostMapping("/windchill/put")
    public AjaxResult windchillPut(@RequestBody SyncSupplierVo reqVo){
        return sysGDPService.insertOrUpdateSupplier(reqVo,getUsername());
    }


    @PreAuthorize("@ss.hasPermi('docdraw:supplier:remove')")
    @Log(title = "windchill删除供应商信息", businessType = BusinessType.DELETE)
    @PostMapping("/windchill/delete")
    public AjaxResult windchillDelete(@RequestBody SyncSupplierVo reqVo){
        return sysGDPService.deleteSupplierFromPTC(reqVo);
    }


    @PreAuthorize("@ss.hasPermi('docdraw:supplier:list')")
//    @Log(title = "windchill端获取供应商列表", businessType = BusinessType.UPDATE)
    @GetMapping("/windchill/getSupplier")
    public AjaxResult windchillGetSupplier(@RequestParam Long tenantId){

        List<SysSupplier> result = new ArrayList<>();
        SysDept dept = new SysDept();
        dept.setParentId(tenantId);
        dept.setStatus(UserConstants.DEPT_NORMAL);
        List<SysDept> sysDepts = deptService.selectDeptList(dept);
        for (SysDept sysDept : sysDepts) {
            SysSupplier sysSupplier = sysSupplierMapper.selectSysSupplierBySupplierId(sysDept.getDeptId());
            result.add(sysSupplier);
        }
        return AjaxResult.success(result);
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('supplier:user:list')")
    @GetMapping("/user")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }



    @PreAuthorize("@ss.hasPermi('supplier:user:list')")
    @GetMapping("/supplier/role")
    public AjaxResult list()
    {
        List<SysRole> roles = new ArrayList<>();
        List<SysRole> sysRoles = roleService.selectRoleAll();

        sysRoles.forEach(sysRole -> {
            String roleKey = sysRole.getRoleKey();
            if("supplierRoot".equals(roleKey) || "supplier".equals(roleKey)){
                roles.add(sysRole);
            }
        });

        return success(roles);
    }





    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('supplier:user:add')")
    @Log(title = "创建供应商账号", businessType = BusinessType.INSERT)
    @PostMapping("/user/add")
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        // 一个供应商部门只能创建一个供应商管理员 和10个供应商
        Long deptId = user.getDeptId();
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);
        List<SysUser> sysUsers = userService.selectUserList(sysUser);


        Long roleId = user.getRoleId();
        SysRole sysRole = roleService.selectRoleById(roleId);
        if(ObjectUtil.isNull(sysRole)){
            return error("请选择供应商角色");
        }

        String roleKey = sysRole.getRoleKey();
        if("supplierRoot".equals(roleKey)){
            for (SysUser sysUser1 : sysUsers) {
                if (Objects.equals(sysUser1.getRoleId(), roleId)) {
                    return error("供应商 ["+ deptService.selectDeptById(deptId).getDeptName()+ "] 已有供应商管理员");
                }
            }
        }else if("supplier".equals(roleKey)){
            List<SysUser> suppliers = new ArrayList<>();
            for (SysUser sysUser1 : sysUsers) {
                if (Objects.equals(sysUser1.getRoleId(), roleId)) {
                    suppliers.add(sysUser1);
                }
            }
            if(suppliers.size() >= 10){
                return error("供应商 ["+ deptService.selectDeptById(deptId).getDeptName()+ "] 普通用户数量为 10 位已达上线");
            }

        }else {
            return error("只能创建供应商管理员和供应商普通用户！");
        }


        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }


}
